import React, { PureComponent } from 'react'
import { connect, history } from '@umijs/max'
import {
  Button, DatePicker, Form, Input, message, Popconfirm, Radio, Select, Tabs, TreeSelect, Upload, Switch,
} from 'antd'
import _ from 'lodash'
import list2tree from 'list2tree'
import moment from 'moment'
import {
  BreadcrumbBar, CreateDiffEditor, ProTable, ProTableOptions,
} from '@/components'
import { getHashParameterByName } from '@/utils/helper'
import { regExp } from '@/utils/regExp'
import { TestModal } from './page-components'
import styles from './index.less'
import { getProjectId, SUAN_PAN } from '@/utils/https'

const { Item } = Form
const { TextArea } = Input
const { Option } = Select
const { TabPane } = Tabs
const { Dragger } = Upload

const descId = window.location.hash?.split('id=')?.[1]
const menus = [{ name: '我的API' }, { name: `${descId ? '编辑' : '新建'}API` }]
const descRe = regExp.name(2, 32)
const urlRe = regExp.url()
const pathRe = regExp.path()
const txtRe = regExp.proName(1, 128)
const lenRe = regExp.proName(1, 128)
const urlLenRe = regExp.proName(1, 8182)
const tokenLenRe = regExp.proName(1, 4096)

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = dataIndex === 'operation' ? inputType(record) : (
    <Form.Item
      name={dataIndex}
      style={{ margin: 0 }}
      rules={[
        {
          required: true,
          message: `请输入${title}`,
        },
        // {
        //   pattern: new RegExp(lenRe.reg, 'g'),
        //   message: lenRe.text,
        // },
      ]}
    >
      <Input placeholder={`请输入${title}`} />
    </Form.Item>
  )

  return (
    <td {...restProps}>
      {editing ? (
        inputNode
      ) : (
        children
      )}
    </td>
  )
}

const getNavTreeDataFunc2 = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'dirName',
  },
})

@connect(({ registerApiCreate }) => ({ ...registerApiCreate }))
class RegisterApiCreate extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      activeTabKey: '1',
      fileList: [],
      headerColumns: [
        {
          title: '参数名称',
          dataIndex: 'fieldName',
          width: '35%',
          key: 'fieldName',
          editable: true,
        },
        {
          title: '参数值',
          dataIndex: 'fieldValue',
          width: '35%',
          key: 'fieldValue',
          editable: true,
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '30%',
          key: 'operation',
          editable: true,
          inputType: (record) => (
            <ProTableOptions>
              <span onClick={this.onFieldSaveClick}>保存</span>
              {
                // 此处作删除使用
                (!record.fieldName || record.fieldName === '') ? (
                  <span onClick={() => { this.onDelClick(record) }}>取消</span>
                ) : (
                  <span onClick={this.onFieldCancelClick}>取消</span>
                )
              }
            </ProTableOptions>
          ),
          render: (text, record) => (
            <ProTableOptions>
              {
                this.props?.formData?.isView ? (
                  <>
                    <span className={styles.disabled}>编辑</span>
                    <span className={styles.disabled}>删除</span>
                  </>
                ) : (
                  <>
                    <span onClick={() => this.onEditClick(record)}>编辑</span>
                    <Popconfirm
                      title="你确定要删除这个字段吗？"
                      okText="确定"
                      cancelText="取消"
                      onConfirm={() => this.onDelClick(record)}
                    >
                      <span>
                        删除
                      </span>
                    </Popconfirm>
                  </>
                )
              }
            </ProTableOptions>
          ),
        },
      ],
      requestHeaderData: [],
      rawJson: '',
      apiLoading: false,
    }
    this.testModalRef = React.createRef()

    this.editorObjectEditId = `${Math.random()}`
    this.dataSourceForm = React.createRef()
    this.tableData = React.createRef()
    this.objectParamsRef = React.createRef()
  }

  componentDidMount() {
    this.queryGetApiGroup()
    this.descId = getHashParameterByName('id') || ''
    this.descId && this.viewDetail(this.descId)
    const dirKey = getHashParameterByName('dirKey') || ''
    if (dirKey) {
      this.dataSourceForm.current?.setFieldsValue({ apiGroupId: dirKey })
    }
  }

  // 查看详情
  viewDetail = (id) => {
    this.props.dispatch({
      type: 'registerApiCreate/queryGetDataApiDetailById',
      params: {
        id,
      },
      cb: (res) => {
        const { status, msg, data = {} } = res || {}
        if (status === 200) {
          const {
            apiName, apiPath, apiProtocol, apiMethod, apiGroupId, apiDesc, tableName, dataApiRegisterDomain, authType, isSecurity,
          } = data

          const {
            apiHttpAuth, apiHttpRequestBody, apiHttpRequestHeader, httpRequestMethod, url,
          } = dataApiRegisterDomain

          this.dataSourceForm.current?.setFieldsValue({
            apiName, apiPath, apiProtocol, apiMethod, apiGroupId, apiDesc, tableName, httpRequestMethod, url, authType1: authType ? 1 : 0, isSecurity: !!isSecurity,
          })

          this.initParams(apiHttpAuth, apiHttpRequestBody, apiHttpRequestHeader)
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  // 初始化页面参数
  initParams = (apiHttpAuth, apiHttpRequestBody, apiHttpRequestHeader) => {
    const { params } = apiHttpRequestHeader || {}
    // const { expressionParamList, jsScript, responseRawJson } = previewExpressRequest || {}

    const requestHeaderData = []
    params?.map((item, index) => {
      requestHeaderData.push({
        fieldName: item.name,
        fieldValue: item.value,
        key: index,
      })
      return null
    })

    const { body = '' } = apiHttpRequestBody || {}
    this.setState({
      requestHeaderData,
      rawJson: body,
    })

    // 认证类型为 自定义文件 的情况
    const {
      authType, advancedFileName, advancedCacheKey, expires,
    } = apiHttpAuth || {}
    if (authType === 'jar') {
      const tempExpires = expires && moment(expires, 'YYYY-MM-DD')
      this.dataSourceForm.current.setFieldsValue({ expires: tempExpires })

      this.setState({
        fileList: [{
          uid: Math.random(),
          name: advancedFileName,
          status: 'done',
        }],
        advancedCacheKey,
        advancedFileName,
      })
    }

    const fieldObj = {
      ...apiHttpAuth,
      ...apiHttpRequestBody,
    }
    delete fieldObj.expires
    this.dataSourceForm.current.setFieldsValue(fieldObj)

    // const { id, isView } = this.props?.history?.location?.query || {};
    // (id || formData?.isGoBack) && !isView && this.testData(true, body)
  }

  // 获取API分组
  queryGetApiGroup = () => {
    this.props.dispatch({
      type: 'registerApiCreate/queryGetApiGroup',
      params: {},
      cb: (res) => {
        this.setState({
          apiGroupList: getNavTreeDataFunc2(res || []),
        })
      },
    })
  }

  // 接口测试
  testData = (isInit = false, resBody = '') => {
    const { editingKey, activeTabKey, advancedCacheKey } = this.state

    if (editingKey || editingKey === 0) {
      this.tableData.current.validateFields()
      this.setState({
        activeTabKey: '2',
      }, () => {
        this.tableData.current.validateFields()
      })
      return null
    }

    const headerParams = []
    this.state.requestHeaderData?.map(item => {
      const obj = {
        name: item.fieldName,
        value: item.fieldValue,
      }
      headerParams.push(obj)
      return null
    })

    const bodyRaw = this.objectParamsRef?.current?.getEditorValue() || ''

    this.dataSourceForm.current.validateFields().then(values => {
      const {
        httpRequestMethod, url, authType, accessKey, accessSecret, accessToken, expires, bodyType, advanceClassReference, advanceMethodName, advancedFilePath,

        apiMethod, apiDesc, apiGroupId, apiProtocol, apiPath, apiName, authType1,
      } = values

      this.setState({
        apiLoading: true,
      })

      this.props.dispatch({
        type: 'registerApiCreate/queryTestRegisterApi',
        params: {
          apiDesc,
          apiGroupId,
          apiProtocol,
          apiPath,
          apiName,
          apiType: 2,
          apiMethod,
          httpRequestMethod,
          url,
          authType: authType1,
          apiHttpAuth: {
            authType,
            accessKey,
            accessSecret,
            accessToken,
            expires: expires && `${moment(expires).format('YYYY-MM-DD')} 23:59:59` || undefined,
            advanceClassReference,
            advanceMethodName,
            advancedFilePath,
            advancedCacheKey,
          },
          apiHttpRequestHeader: {
            params: headerParams,
          },
          apiHttpRequestBody: {
            contentType: bodyType || 'application/json',
            body: bodyRaw || resBody,
          },
        },
        cb: (res) => {
          const { data, msg, status } = res || {}
          this.setState({
            apiLoading: false,
          })
          if (status === 200) {
            // message.success('操作成功')
            this.testModalRef?.current?.toggleModal(data)
          } else {
            message.error(msg || '服务端错误')
          }
        },
      })
    }).catch(errorInfo => {
      // 提升用户体验，选中了认证必填项，但在其他tab页签，通过message.warn提示并切换tab页
      const {
        authType, advancedFilePath, accessKey, accessSecret, accessToken, advanceClassReference, advanceMethodName, expires,
      } = errorInfo?.values || {}
      if (activeTabKey !== '1' && authType !== 'noauth' && (!advancedFilePath || !accessKey || !accessSecret || !accessToken || !advanceClassReference || !advanceMethodName || !expires)) {
        message.warn('请完善必填项')
        this.setState({
          activeTabKey: '1',
        })
      }
    })
    return null
  }

  // 保存
  save = (isInit = false, resBody = '') => {
    const {
      editingKey, activeTabKey, advancedCacheKey, advancedFileName,
    } = this.state

    if (editingKey || editingKey === 0) {
      this.tableData.current.validateFields()
      this.setState({
        activeTabKey: '2',
      }, () => {
        this.tableData.current.validateFields()
      })
      return null
    }

    const headerParams = []
    this.state.requestHeaderData?.map(item => {
      const obj = {
        name: item.fieldName,
        value: item.fieldValue,
      }
      headerParams.push(obj)
      return null
    })

    const bodyRaw = this.objectParamsRef?.current?.getEditorValue() || ''

    this.dataSourceForm.current.validateFields().then(values => {
      const {
        httpRequestMethod, url, authType, accessKey, accessSecret, accessToken, expires, bodyType, advanceClassReference, advanceMethodName, advancedFilePath,

        apiMethod, apiDesc, apiGroupId, apiProtocol, apiPath, apiName, datasourceId, authType1, isSecurity,
      } = values

      const params = this.descId ? { id: this.descId } : {}

      this.setState({
        apiLoading: true,
      })

      this.props.dispatch({
        type: 'registerApiCreate/querySaveRegisterApi',
        params: {
          ...params,
          apiDesc,
          apiGroupId,
          apiProtocol,
          apiPath,
          apiName,
          apiType: 2, // 写死
          datasourceId,
          apiMethod,
          authType: authType1,
          httpRequestMethod,
          url,
          apiHttpAuth: {
            authType,
            accessKey,
            accessSecret,
            accessToken,
            expires: expires && `${moment(expires).format('YYYY-MM-DD')} 23:59:59` || undefined,
            advanceClassReference,
            advanceMethodName,
            advancedFilePath,
            advancedCacheKey,
            advancedFileName,
          },
          apiHttpRequestHeader: {
            params: headerParams,
          },
          apiHttpRequestBody: {
            contentType: bodyType || 'application/json',
            body: bodyRaw || resBody,
          },
          isSecurity: isSecurity ? 1 : 0,
        },
        cb: (res) => {
          const { msg = '服务端错误', status } = res || {}
          this.setState({
            apiLoading: false,
          })
          if (status === 200) {
            history.push('/data-service/api-manage/my-api')
            message.success('操作成功')
          } else {
            message.error(msg || '服务端错误')
          }
        },
      })
    }).catch(errorInfo => {
      // 提升用户体验，选中了认证必填项，但在其他tab页签，通过message.warn提示并切换tab页
      const {
        authType, advancedFilePath, accessKey, accessSecret, accessToken, advanceClassReference, advanceMethodName, expires,
      } = errorInfo?.values || {}
      if (activeTabKey !== '1' && authType !== 'noauth' && (!advancedFilePath || !accessKey || !accessSecret || !accessToken || !advanceClassReference || !advanceMethodName || !expires)) {
        message.warn('请完善必填项')
        this.setState({
          activeTabKey: '1',
        })
      }
    })
    return null
  }

  // 编辑参数按钮回调
  onEditClick = (record) => {
    if (this.state.editingKey || this.state.editingKey === 0) {
      message.warning('请先完成当前参数的编辑')
      return
    }
    this.tableData.current.setFieldsValue(record)
    this.setState({
      editingKey: record.key,
    })
  }

  // 删除参数按钮回调
  onDelClick = (record) => {
    const arr = []
    this.state.requestHeaderData.map((item) => {
      if (item.key !== record.key) {
        arr.push(item)
      }
      return null
    })
    // 删除时按顺序重置key
    arr.map((item, index) => {
      item.key = index
      return null
    })
    this.setState({
      requestHeaderData: arr,
      editingKey: undefined,
    })
  }

  // 保存参数修改
  onFieldSaveClick = () => {
    this.tableData.current.validateFields().then(values => {
      const { requestHeaderData, editingKey } = this.state
      const dataObj = requestHeaderData.find((item) => item.key === editingKey)
      dataObj.fieldName = values.fieldName
      dataObj.fieldValue = values.fieldValue
      this.setState({
        editingKey: undefined,
        requestHeaderData: _.clone(requestHeaderData),
      })
    })
  }

  // 取消参数修改
  onFieldCancelClick = () => {
    const { requestHeaderData } = this.state
    this.setState({
      editingKey: undefined,
      requestHeaderData: _.clone(requestHeaderData),
    })
  }

  // 新增参数
  onAddClick = () => {
    if (this.state.editingKey || this.state.editingKey === 0) {
      message.warning('请先完成当前参数的编辑')
      return
    }
    const { requestHeaderData } = this.state
    // eslint-disable-next-line react/no-access-state-in-setstate
    const len = requestHeaderData?.length
    requestHeaderData.push({
      fieldName: undefined,
      fieldValue: undefined,
      key: len,
    })
    this.tableData.current.resetFields()
    this.setState({
      editingKey: len,
      requestHeaderData: _.clone(requestHeaderData),
    })
  }

  render() {
    const {
      apiGroupList, fileList, activeTabKey, headerColumns, requestHeaderData, rawJson, apiLoading,
    } = this.state
    return (
      <div className={styles.my_api_create}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.back_bar}>
          <i
            className="iconfont icon-zuo"
            onClick={() => { history.push('/data-service/api-manage/my-api') }}
            style={{ cursor: 'pointer' }}
          />
          <span onClick={() => { history.push('/data-service/api-manage/my-api') }}>注册API</span>
        </div>
        <div className={styles.container}>
          <Form
            ref={this.dataSourceForm}
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 10 }}
            autoComplete="off"
          >
            <Item>
              <div className={styles.column}>基础设置</div>
            </Item>
            <Item
              label="API名称"
              name="apiName"
              rules={[
                { required: true, message: '请输入API名称' },
                {
                  pattern: new RegExp(descRe.reg, 'g'),
                  message: descRe.text,
                }]}
            >
              <Input placeholder="请输入API名称" />
            </Item>
            <Item
              label="API Path"
              name="apiPath"
              rules={[
                { required: true, message: '请输入API Path' },
                {
                  pattern: new RegExp(txtRe.reg, 'g'),
                  message: txtRe.text,
                },
                {
                  pattern: new RegExp(pathRe.reg, 'g'),
                  message: pathRe.text,
                },
              ]}
            >
              <Input placeholder="请输入API Path" />
            </Item>
            <Item
              label="API协议"
              name="apiProtocol"
              rules={[{ required: true, message: '请选择API协议' }]}
              initialValue="0"
            >
              <Radio.Group>
                <Radio value="0">HTTP</Radio>
                {/* <Radio value="1">HTTPS</Radio> */}
              </Radio.Group>
            </Item>
            <Item
              label="请求方式"
              name="apiMethod"
              rules={[{ required: true, message: '请选择API协议' }]}
              initialValue="GET"
            >
              <Radio.Group>
                <Radio value="GET">GET</Radio>
                <Radio value="POST">POST</Radio>
              </Radio.Group>
            </Item>
            <Item
              label="认证方式"
              name="authType1"
              rules={[{ required: true, message: '请选择authType' }]}
              initialValue={0}
            >
              <Radio.Group>
                <Radio value={0}>ApiToken认证</Radio>
                <Radio value={1}>UserToken认证</Radio>
              </Radio.Group>
            </Item>
            <Item
              label="API分组"
              name="apiGroupId"
              rules={[
                { required: true, message: '请选择API分组' },
              ]}
            >
              <TreeSelect
                allowClear
                showSearch
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                treeData={apiGroupList}
                placeholder="请输入选择目录"
                treeDefaultExpandAll
                filterTreeNode={(input, treeNode) => treeNode?.dirName.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                fieldNames={{
                  label: 'dirName', value: 'id', children: 'children',
                }}
              />
            </Item>
            <Item
              label="出入参是否加密"
              name="isSecurity"
              initialValue={false}
              valuePropName="checked"
            >
              <Switch />
            </Item>
            <Item
              label="描述"
              name="apiDesc"
            >
              <TextArea rows={2} />
            </Item>
            <Item>
              <div className={styles.column}>后端服务接口</div>
            </Item>
            {/* 后端让去掉 */}
            {/* <Item */}
            {/*  label="协议" */}
            {/*  name="apiProtocol2" */}
            {/*  rules={[{ required: true, message: '请选择协议' }]} */}
            {/*  initialValue="http/https" */}
            {/* > */}
            {/*  <Select */}
            {/*    showSearch */}
            {/*    placeholder="请选择协议" */}
            {/*    filterOption={(input, option) => option.props?.title */}
            {/*      ?.toLowerCase() */}
            {/*      ?.indexOf(input?.toLowerCase()) >= 0} */}
            {/*  > */}
            {/*    <Option key="http/https">http/https</Option> */}
            {/*    /!* <Option key="webService">webService</Option> *!/ */}
            {/*  </Select> */}
            {/* </Item> */}
            <Item
              label="请求方式"
              name="httpRequestMethod"
              rules={[{ required: true, message: '请选择请求方式' }]}
              initialValue="GET"
            >
              <Radio.Group>
                <Radio value="GET">GET</Radio>
                <Radio value="POST">POST</Radio>
              </Radio.Group>
            </Item>
            <Item
              label="URL"
              name="url"
              rules={[
                { required: true, message: '请输入URL' },
                {
                  pattern: new RegExp(urlRe.reg, 'g'),
                  message: urlRe.text,
                },
                {
                  pattern: new RegExp(urlLenRe.reg, 'g'),
                  message: urlLenRe.text,
                },
              ]}
            >
              <Input placeholder="请输入URL" />
            </Item>

            <Item wrapperCol={{ span: 12 }}>
              <Tabs
                defaultActiveKey="1"
                activeKey={activeTabKey}
                onChange={(e) => { this.setState({ activeTabKey: e }) }}
              >
                <TabPane tab="认证" key="1">
                  <Item
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    label="类型"
                    name="authType"
                    rules={[{ required: true, message: '请选择认证类型' }]}
                    initialValue="noauth"
                  >
                    <Select
                      placeholder="请选择认证类型"
                    >
                      <Option value="noauth">无</Option>
                      <Option value="sign">API密钥</Option>
                      <Option value="token">Token令牌</Option>
                      <Option value="jar">自定义认证</Option>
                    </Select>
                  </Item>
                  <Item shouldUpdate noStyle>
                    {(form) => form.getFieldValue('authType') === 'sign' && (
                      <>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="key"
                          name="accessKey"
                          rules={[
                            { required: true, message: '请输入key' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input placeholder="请输入key" />
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="value"
                          name="accessSecret"
                          rules={[
                            { required: true, message: '请输入value' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input placeholder="请输入value" />
                        </Item>
                      </>
                    )}
                  </Item>
                  <Item shouldUpdate noStyle>
                    {(form) => form.getFieldValue('authType') === 'token' && (
                      <Item
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        label="Token"
                        name="accessToken"
                        rules={[
                          { required: true, message: '请输入Token' },
                          {
                            pattern: new RegExp(tokenLenRe.reg, 'g'),
                            message: tokenLenRe.text,
                          },
                        ]}
                      >
                        <Input placeholder="请输入Token" />
                      </Item>
                    )}
                  </Item>
                  <Item shouldUpdate noStyle>
                    {(form) => form.getFieldValue('authType') === 'jar' && (
                      <>
                        <Item
                          wrapperCol={{ span: 24 }}
                          name="advancedFilePath"
                          rules={[{ required: true, message: '请上传jar包' }]}
                        >
                          <Dragger
                            name="file"
                            // multiple={false}
                            accept=".jar"
                            maxCount={1}
                            action={`${SUAN_PAN}/api/v1/integration/api/http/uploadJar`}
                            headers={{ 'X-Project-Id': getProjectId() }}
                            fileList={fileList}
                            onChange={(info) => {
                              if (info.file.status !== 'uploading') {
                                // console.log(info.file, info.fileList);
                              }
                              if (info.file.status === 'done') {
                                const res = info.file.response
                                if (res.status === 200) {
                                  message.success(`${info.file.name} 上传成功`)
                                  this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: info?.file?.response?.data?.filePath })
                                  const advancedCacheKey = info?.file?.response?.data?.cacheKey
                                  const advancedFileName = info?.file?.name || ''
                                  this.setState({
                                    advancedCacheKey,
                                    advancedFileName,
                                  })
                                } else {
                                  message.warning(res.msg, 3)
                                  info.file.status = 'error'
                                  info.file.response = res.msg || '上传错误'
                                  info.fileList.find((item) => item.uid === info.file.uid).status = 'error'
                                }
                              } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 上传失败.`)
                              }
                              if (info.file.status === 'removed') {
                                this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: '' })
                              }
                              this.setState({
                                fileList: info?.fileList || [],
                              })
                            }}
                            onRemove={() => {
                              this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: '' })
                            }}
                            style={{ height: '200px' }}
                          >
                            <p className="ant-upload-drag-icon">
                              <i className="iconfont icon-cunchu" />
                            </p>
                            <p className="ant-upload-text">将文件拖拽至此，或单击直接上传</p>
                            <p className="ant-upload-hint">支持扩展名：jar</p>
                          </Dragger>
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="类名"
                          name="advanceClassReference"
                          rules={[
                            { required: true, message: '请输入类名' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input placeholder="请输入类名" />
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="方法名"
                          name="advanceMethodName"
                          rules={[
                            { required: true, message: '请输入方法名' },
                            {
                              pattern: new RegExp(lenRe.reg, 'g'),
                              message: lenRe.text,
                            },
                          ]}
                        >
                          <Input placeholder="请输入方法名" />
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="变量有效期"
                          name="expires"
                          rules={[{ required: true, message: '请输入变量有效期' }]}
                        >
                          <DatePicker
                            disabledDate={this.disabledDate}
                            placeholder="请输入变量有效期"
                            style={{ width: '100%' }}
                          />
                        </Item>
                      </>
                    )}
                  </Item>
                </TabPane>
                <TabPane tab="请求头" key="2">
                  <Item wrapperCol={{ span: 24 }}>
                    <Form ref={this.tableData} component={false}>
                      <ProTable
                        rowKey={() => (Math.random())}
                        loading={false}
                        showQuickJumper={false}
                        showSizeChanger={false}
                        pagination={false}
                        dataSource={requestHeaderData}
                        components={{
                          body: {
                            cell: EditableCell,
                          },
                        }}
                        columns={headerColumns.map(col => {
                          if (!col.editable) {
                            return col
                          }
                          return {
                            ...col,
                            onCell: (record) => ({
                              record,
                              dataIndex: col.dataIndex,
                              title: col.title,
                              inputType: col.inputType,
                              editing: this.state.editingKey === record.key,
                            }),
                          }
                        })}
                        scroll={{ y: 157 }}
                      />
                      <div className={styles.add_item}>
                        <Button
                          type="link"
                          onClick={this.onAddClick}
                        >
                          <i className="iconfont icon-tianjia1" />
                          新增参数
                        </Button>
                      </div>
                    </Form>
                  </Item>
                </TabPane>
                <TabPane tab="请求体" key="3">
                  <Item
                    label="类型"
                    name="bodyType"
                    rules={[{ required: true, message: '请选择请求体类型' }]}
                    initialValue="application/json"
                  >
                    <Select>
                      <Option value="application/json">application/json</Option>
                    </Select>
                  </Item>
                  <Item shouldUpdate noStyle>
                    {(form) => form.getFieldValue('bodyType') === 'application/json' && (
                      <div className={styles.json_diff_editor}>
                        <CreateDiffEditor
                          // readOnly={isView}
                          restData={rawJson || ''}
                          ref={this.objectParamsRef}
                          language="json"
                          theme="vs"
                          editorId={this.editorObjectEditId}
                        />
                      </div>
                    )}
                  </Item>
                </TabPane>
              </Tabs>
            </Item>
          </Form>
        </div>
        <div className={styles.edit_footer}>
          <Button
            className={styles.edit_btn}
            onClick={() => { history.push('/data-service/api-manage/my-api') }}
          >
            取消
          </Button>
          <Button
            loading={apiLoading}
            className={styles.edit_btn}
            type="primary"
            onClick={this.testData}
          >
            API测试
          </Button>
          <Button
            className={styles.edit_btn}
            type="primary"
            onClick={this.save}
          >
            确定
          </Button>
        </div>
        <TestModal ref={this.testModalRef} />
      </div>
    )
  }
}

export default RegisterApiCreate
